package com.example.pungolo.journal.view;

import java.lang.ref.WeakReference;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Point;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.ImageView;

//http://developer.android.com/training/displaying-bitmaps/process-bitmap.html
class BitmapWorkerTask extends AsyncTask<String, Void, Bitmap> {
  private final WeakReference<DiaryPageView> diaryPageViewReference;
  private String imagePath = "";
  private Point maxSize;
  private Rect crop;

  public BitmapWorkerTask(DiaryPageView diaryPageView, Point maxSize, Rect crop) {
    // Use a WeakReference to ensure the ImageView can be garbage collected
    this.diaryPageViewReference = new WeakReference<DiaryPageView>(diaryPageView);
    this.crop = crop;
    this.maxSize = maxSize;
  }

  // Decode image in background.
  @Override
  protected Bitmap doInBackground(String... params) {
    imagePath = params[0];
    Bitmap t, m = BitmapFactory.decodeFile(imagePath);
    if (this.crop != null) {
      t = Bitmap.createBitmap(m, this.crop.left, this.crop.top, this.crop.width(), this.crop.height(), null, true);
      if (m != t) {
        m.recycle();
        m = t;
      }
    }
    
    if (this.maxSize != null)
      if (m.getHeight() > this.maxSize.y || m.getWidth() > this.maxSize.x) {
        Log.i("pungolo-journal", "La foto è più grande dello schermo. Effettuo un riscalamento.");
        float xScale = (float)this.maxSize.x / (float)m.getWidth();
        float yScale = (float)this.maxSize.y / (float)m.getHeight();
        float scale = Math.min(xScale, yScale);
        int w = (int)(m.getWidth() * scale);
        int h = (int)(m.getHeight() * scale);
        t = Bitmap.createScaledBitmap(m, w, h, true);
        if (m != t) {
          m.recycle();
          m = t;
        }
      }
    
    return m;
  }

  // Once complete, see if ImageView is still around and set bitmap.
  @Override
  protected void onPostExecute(Bitmap bitmap) {
    if (diaryPageViewReference != null && bitmap != null) {
      final DiaryPageView diaryPageView = diaryPageViewReference.get();
      if (diaryPageView != null) {
        diaryPageView.setImageBitmap(bitmap);
      }
    }
  }
}
